package com.vilen.servlet;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.vilen.model.ResultModel;
import com.vilen.model.Weather;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by vilen on 2015/4/2.
 */
@WebServlet(name="WeatherServlet",urlPatterns="/WeatherServlet")
public class WeatherServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String city = "库尔勒";
        //http://api.map.baidu.com/telematics/v3/weather?location=库尔勒&output=json&ak=eF0eRGFALjkkqTx6sR8TwyWZ
//        String urlStr = "http://api.map.baidu.com/telematics/v3/weather?location="+
//                URLEncoder.encode(city,"utf-8")+"&output=json&ak=";
//        URL url = new URL(urlStr);
//        //获得链接
//        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//        //得到输入流
//        InputStream inputStream = connection.getInputStream();
//        //字节流--》字符流
//        ByteArrayOutputStream baos = new ByteArrayOutputStream();
//        byte[] b = new byte[1024];//byte数组
//        int n=0;//临时变量
//        while ((n=inputStream.read(b))!=-1){
//            baos.write(b,0,n);
//        }
//        String jsonStr=baos.toString("utf-8");
//        baos.close();//关闭流
//        inputStream.close();//关闭
        String jsonStr= "{\"error\":0,\"status\":\"success\",\"date\":\"2015-04-02\",\"results\":[{\"currentCity\":\"库尔勒\",\"pm25\":\"500\",\"index\":[{\"title\":\"穿衣\",\"zs\":\"较舒适\",\"tipt\":\"穿衣指数\",\"des\":\"建议着薄外套、开衫牛仔衫裤等服装。年老体弱者应适当添加衣物，宜着夹克衫、薄毛衣等。\"},{\"title\":\"洗车\",\"zs\":\"较适宜\",\"tipt\":\"洗车指数\",\"des\":\"较适宜洗车，未来一天无雨，风力较小，擦洗一新的汽车至少能保持一天。\"},{\"title\":\"旅游\",\"zs\":\"适宜\",\"tipt\":\"旅游指数\",\"des\":\"天气较好，风稍大，但温度适宜，总体来说还是好天气。这样的天气适宜旅游，您可以尽情享受大自然的风光。\"},{\"title\":\"感冒\",\"zs\":\"较易发\",\"tipt\":\"感冒指数\",\"des\":\"天凉，昼夜温差较大，较易发生感冒，请适当增减衣服，体质较弱的朋友请注意适当防护。\"},{\"title\":\"运动\",\"zs\":\"较适宜\",\"tipt\":\"运动指数\",\"des\":\"阴天，较适宜进行各种户内外运动。\"},{\"title\":\"紫外线强度\",\"zs\":\"最弱\",\"tipt\":\"紫外线强度指数\",\"des\":\"属弱紫外线辐射天气，无需特别防护。若长期在户外，建议涂擦SPF在8-12之间的防晒护肤品。\"}],\"weather_data\":[{\"date\":\"周四 04月02日 (实时：10℃)\",\"dayPictureUrl\":\"http://api.map.baidu.com/images/weather/day/fuchen.png\",\"nightPictureUrl\":\"http://api.map.baidu.com/images/weather/night/duoyun.png\",\"weather\":\"浮尘转多云\",\"wind\":\"北风3-4级\",\"temperature\":\"19 ~ 10℃\"},{\"date\":\"周五\",\"dayPictureUrl\":\"http://api.map.baidu.com/images/weather/day/fuchen.png\",\"nightPictureUrl\":\"http://api.map.baidu.com/images/weather/night/duoyun.png\",\"weather\":\"浮尘转多云\",\"wind\":\"北风3-4级\",\"temperature\":\"14 ~ 6℃\"},{\"date\":\"周六\",\"dayPictureUrl\":\"http://api.map.baidu.com/images/weather/day/qing.png\",\"nightPictureUrl\":\"http://api.map.baidu.com/images/weather/night/qing.png\",\"weather\":\"晴\",\"wind\":\"微风\",\"temperature\":\"13 ~ 7℃\"},{\"date\":\"周日\",\"dayPictureUrl\":\"http://api.map.baidu.com/images/weather/day/duoyun.png\",\"nightPictureUrl\":\"http://api.map.baidu.com/images/weather/night/qing.png\",\"weather\":\"多云转晴\",\"wind\":\"微风\",\"temperature\":\"18 ~ 8℃\"}]}]}";

        //解析json
        ResultModel rm = JSONObject.parseObject(jsonStr, ResultModel.class);
//        System.out.println(rm.getDate());
        JSONArray jsonResult = JSON.parseObject(jsonStr).getJSONArray("results");

        List<Weather> wList  = new ArrayList<Weather>();
        for (int i = 0; i < jsonResult.size(); i++) {
            JSONArray jsonWeatherData = jsonResult.getJSONObject(i).getJSONArray("weather_data");
            List<Weather> weathers = JSONObject.parseArray(jsonWeatherData.toJSONString(), Weather.class);
            wList.addAll(weathers);
        }
//        System.out.println(wList);
        rm.setResults(wList);
        rm.setCity(city);
        //数据保存
        req.setAttribute("weather",rm);

        req.getRequestDispatcher("/index.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doPost(req, resp);
    }
}
